// Copyright 2007-2013 metaio GmbH. All rights reserved.
package com.panjing.ar.Activity;

import java.util.List;
import java.util.Map;
import java.util.Timer;

import android.annotation.SuppressLint;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.LinearLayout;

import com.cmcc.ar.R;
import com.metaio.sdk.ARViewActivity;
import com.metaio.sdk.MetaioDebug;
import com.metaio.sdk.jni.IGeometry;
import com.metaio.sdk.jni.IMetaioSDKCallback;
import com.metaio.sdk.jni.Rotation;
import com.metaio.sdk.jni.TrackingValues;
import com.metaio.sdk.jni.TrackingValuesVector;
import com.metaio.sdk.jni.Vector3d;
import com.metaio.sdk.jni.Vector4d;
import com.metaio.tools.io.AssetsManager;
import com.panjing.ar.Common.ConfigSet;
import com.panjing.ar.Common.Constants;
import com.panjing.ar.Common.MovieView;
import com.panjing.ar.Common.ResourceItem;
import com.panjing.ar.Common.SqlitDataBase;
import com.panjing.ar.Common.TouchView;
import com.panjing.ar.Common.downLoadFile;

public class MoiveActivity extends ARViewActivity 
{
	private final String TAG = "MoiveActivity";
	private IGeometry mModel;
	private IGeometry mImagePlane;
	private MetaioSDKCallbackHandler mCallbackHandler;
	private boolean isAlreadyOpen = false;
	private TouchView touchView;
	private downLoadFile download;
	private ConfigSet resourceList;
	private MovieView movieView;

	
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		
		mModel = null;
		mImagePlane = null;
		mCallbackHandler = new MetaioSDKCallbackHandler();
		touchView = (TouchView) mGUIView.findViewById(R.id.display_view);
		movieView = (MovieView) mGUIView.findViewById(R.id.movie_view);
//		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
		
		download = new downLoadFile();
		resourceList = SqlitDataBase.getInstance(MoiveActivity.this).getConfigResource(3);
		
		LinearLayout buttonBar = (LinearLayout)mGUIView.findViewById(R.id.buttonBar);
		buttonBar.setVisibility(View.GONE);
	}
	
    
	public void onImageButtonClick(View v)
	{
		
	}
	
	public void onMovieButtonClick(View v)
	{
		
	}
	
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data){
    	isAlreadyOpen = false;
		runOnUiThread(new Runnable() 
		{
			@Override
			public void run() 
			{
				touchView.setVisibility(View.GONE);
			}
		});
    }
	
	@Override
	protected int getGUILayout() 
	{
		// Attaching layout to the activity
		return R.layout.tutorial1; 
	}


	public void onButtonClick(View v)
	{
		finish();
	}
	
	
	@Override
	protected void loadContents() 
	{
		try
		{
			
			 AssetsManager.extractAllAssets(getApplicationContext(),true);
			// Getting a file path for tracking configuration XML file
//			String trackingConfigFile = AssetsManager.getAssetPath("SingleResource/Assets1/TrackingData_MarkerlessFast.xml");
			String trackingConfigFile = Constants.getPicBasePath()+resourceList.xmlResource.resrouceID+"/"
																				+resourceList.xmlResource.resourceXml;

			// Assigning tracking configuration
			boolean result = metaioSDK.setTrackingConfiguration(trackingConfigFile); 
			MetaioDebug.log("Tracking data loaded: " + result); 
	        
			// Loading image geometry
			final String imagePath = AssetsManager.getAssetPath("SingleResource/Assets1/frame.png");
			if (imagePath != null)
			{
				mImagePlane = metaioSDK.createGeometryFromImage(imagePath);
				if (mImagePlane != null)
				{
					mImagePlane.setScale(3.0f);
					MetaioDebug.log("Loaded geometry "+imagePath);
				}
				else {
					MetaioDebug.log(Log.ERROR, "Error loading geometry: "+imagePath);
				}
			}
			
			mImagePlane.setVisible(false);
//			mModel.setVisible(false);
			mCallbackHandler.onTrackingEvent(metaioSDK.getTrackingValues());
			

		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}


//	@SuppressLint("NewApi")
//	@Override
//	public void onDrawFrame(){
//		if(movieView.getVisibility() == View.VISIBLE){
//			TrackingValues v = metaioSDK.getTrackingValues().get(0);
//			movieView.setRotation(v.getRotation().getEulerAngleDegrees().getZ());
//		}
//		
//		super.onDrawFrame();
//	}
	
	
	@Override
	protected void onGeometryTouched(IGeometry geometry)
	{
		// Not used in this tutorial
	}
	

	@Override
	protected IMetaioSDKCallback getMetaioSDKCallbackHandler()
	{
		return mCallbackHandler;
	}	
	
	public class MetaioSDKCallbackHandler extends IMetaioSDKCallback {
		@Override
		public void onSDKReady() 
		{
			// show GUI after SDK is ready
			runOnUiThread(new Runnable() 
			{
				@Override
				public void run() 
				{
					mGUIView.setVisibility(View.VISIBLE);
				}
			});
		}
		
 
		private String url = null;
		
		@Override
		public void onTrackingEvent(TrackingValuesVector trackingValues)
		{
			super.onTrackingEvent(trackingValues);

			// We only have one COS, so there can only ever be one TrackingValues structure passed.
			// Play movie if the movie button was selected and we're currently tracking.
			if (trackingValues.isEmpty() || !trackingValues.get(0).isTrackingState())
			{
				isAlreadyOpen = false;
				runOnUiThread(new Runnable() 
				{
					@Override
					public void run() 
					{
						movieView.stopMovie();
						movieView.setVisibility(View.GONE);
						mSurfaceView.setZOrderOnTop(true);
					}
				});
			}
			else
			{
				if(!isAlreadyOpen){
					isAlreadyOpen = true;
					
					new Thread(){
						@Override
						public void run(){
							if(resourceList != null && !resourceList.resourceItem.isEmpty()){
								ResourceItem item = resourceList.resourceItem.get(0);
								if(item != null){
									String display = item.displayConent;
									String filePath = Constants.getPicBasePath()+resourceList.xmlResource.resrouceID+"/"+display;
									String urlPath = Constants.getSingleResource+resourceList.xmlResource.resrouceID+"/"+display;
									
//									if(!item.controlTime.equals("") && !item.controlContent.equals("")){
//										int time = Integer.valueOf(item.controlTime);
//										movieView.setControlTime(time*1000, item.controlContent,item.linkUrl);
//									}
									
									if(!downLoadFile.isFileExit(filePath)){
										url = urlPath;
										traceHandler.sendEmptyMessage(100);
										download.downFile(urlPath, filePath);
									}else{
										url = filePath;
										traceHandler.sendEmptyMessage(100);
									}
								}
							}	
						}
					}.start();
				}
			}
		}
		
		private Handler traceHandler = new Handler(){
			@Override 
	        public void handleMessage(Message msg) {
				movieView.setVisibility(View.VISIBLE);
				Log.d(TAG,"the movie url is "+url);
				ResourceItem item = resourceList.resourceItem.get(0);
				if(!item.controlTime.equals("") && !item.controlContent.equals("")){
					int time = Integer.valueOf(item.controlTime);
					movieView.setControlTime(time*1000, item.controlContent,item.linkUrl);
				}
				
				movieView.startMovie(url);
			}
		};
	}
}
